package com.qqtech.qquan.coupon.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.coupon.enums.CouponBaseBizzTypeDictEnum;
import com.qqtech.qquan.coupon.enums.CouponConst;
import com.qqtech.qquan.coupon.enums.CouponUserObtainWayDictEnum;
import com.qqtech.qquan.coupon.enums.CouponUserStatusDictEnum;
import com.qqtech.qquan.coupon.model.CouponBase;
import com.qqtech.qquan.coupon.model.CouponBaseVo;
import com.qqtech.qquan.coupon.model.CouponUser;
import com.qqtech.qquan.coupon.model.CouponUserQuery;
import com.qqtech.qquan.coupon.model.CouponUserVo;
import com.qqtech.qquan.coupon.service.CouponBaseService;
import com.qqtech.qquan.coupon.service.CouponSysParamService;
import com.qqtech.qquan.coupon.service.CouponUserService;
import com.qqtech.qquan.draw.model.DrawItemVo;
import com.qqtech.qquan.draw.service.DrawItemService;
import com.qqtech.qquan.mall.enums.MallConst;
import com.qqtech.qquan.mall.enums.MallSupplierTypeDictEnum;
import com.qqtech.qquan.mall.model.MallProductSpecVo;
import com.qqtech.qquan.mall.model.MallProductVo;
import com.qqtech.qquan.mall.model.MallShopVo;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.mall.service.MallProductService;
import com.qqtech.qquan.mall.service.MallProductSpecService;
import com.qqtech.qquan.mall.service.MallShopService;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.user.enums.UserMoneyLogTypeDictEnum;
import com.qqtech.qquan.user.model.UserValue;
import com.qqtech.qquan.user.service.UserMoneyLogService;
import com.qqtech.qquan.user.service.UserValueService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/coupon/user")
public class CouponUserController extends BaseWebController<CouponUser, CouponUserQuery> {
	@Resource
	private CouponUserService couponUserService;

	@Resource
	private CouponBaseService couponBaseService;
	
	@Resource
	private MallProductSpecService mallProductSpecService;
	
	@Resource
	private MallSupplierService mallSupplierService;
	
	@Resource
	private MallProductService mallProductService;
	
	@Resource
	private UserMoneyLogService userMoneyLogService;
	
	@Resource
	private DrawItemService drawItemService;
	
	@Resource
	private UserValueService userValueService;
	
	@Resource
	private MallShopService mallShopService;
	
	@Resource
	private CouponSysParamService couponSysParamService;
	
	
	@Override
	protected BaseService<CouponUser> getBaseService() {
		return couponUserService;
	}

	@RequestMapping(value = "/autoExpire")
	@ResponseBody
	public Result autoExpire() {
		Result result = new Result();
		couponUserService.autoExpire();
		return result;
	}

	/**
	 * 服务优惠卷
	 * 
	 * @param couponUserQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/homemakingCoupon")
	@ResponseBody
	public Result homemakingCoupon(@RequestBody CouponUserQuery couponUserQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		List<CouponUserVo> list = couponUserService.getHomemakingCoupon(curUserId,
				couponUserQuery.getHomeMakingTypeId());
		result.put("list", list);
		return result;
	}

	/**
	 * 商城优惠卷
	 * 
	 * @param couponUserQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/mallCoupon")
	@ResponseBody
	public Result mallCoupon(@RequestBody CouponUserQuery couponUserQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		result = couponUserService.getMallOrderCouponList(curUserId, couponUserQuery.getOrderItems(),couponUserQuery.getId());
		return result;
	}
	
	/**
	 * 商城优惠卷
	 * 
	 * @param couponUserQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/qmallCoupon")
	@ResponseBody
	public Result qmallCoupon(@RequestBody CouponUserQuery couponUserQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		result = couponUserService.getQMallOrderCouponList(curUserId, couponUserQuery.getOrderItems(),couponUserQuery.getStyle());
		return result;
	}
	
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/getUnusedCoupon")
	@ResponseBody
	public Result getUnusedCoupon(@RequestBody CouponUserQuery couponUserQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		Integer count;
		count = couponUserService.getUnusedCount(curUserId);
		result.put("myCouponCount", count);
		return result;
	}
	/**
	 * 我的优惠卷
	 * 
	 * @param couponUserQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/managePage")
	@ResponseBody
	public Result managePage(@RequestBody CouponUserQuery couponUserQuery) {
		Result result = new Result();
		Integer curUserId = super.getUserId();
		couponUserQuery.setUserId(curUserId);
		Pageable pageKit = new PageKit(couponUserQuery.getPage(), new PageOrder(Direction.ASC, "status"), new PageOrder(Direction.DESC, "newAt"));
		Page<CouponUserVo> page = couponUserService.queryPageList(couponUserQuery, pageKit);
		CouponBaseVo couponBaseVo = null;
		for (CouponUserVo couponUserVo : page) {
			couponBaseVo = couponBaseService.getById(couponUserVo.getCouponId());
			couponUserVo.setCouponName(couponBaseVo.getName());
			couponUserVo.setBizzType(couponBaseVo.getBizzType());
			couponUserVo.setBizzId(couponBaseVo.getBizzId());
			couponUserVo.setRemark(couponBaseVo.getRemark());
			if(CouponUserObtainWayDictEnum.DRAW.getCode()==couponUserVo.getObtainWay()){
				DrawItemVo drawItemVo=drawItemService.getByCouponId(couponUserVo.getCouponId());
				if(null!=drawItemVo){
					couponUserVo.setDrawImg(drawItemVo.getPathImgs());
				}
			}
			if (couponUserVo.getExpireAt() != null && couponUserVo.getExpireAt().before(TimeUtil.now())) {
				couponUserVo.setStrStatus("已过期");
			} else if (couponUserVo.getStatus().intValue() == CouponUserStatusDictEnum.NOT_USED.getCode()) {
				couponUserVo.setStrStatus("未使用");
			} else if (couponUserVo.getStatus().intValue() == CouponUserStatusDictEnum.BE_USED.getCode()) {
				couponUserVo.setStrStatus("已使用");
			} else {
				couponUserVo.setStrStatus("已过期");
			}
		}

		result.put("page", page);
		return result;
	}
	
	/**
	 * 我的优惠卷
	 * 
	 * @param couponUserQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/toBuy")
	@ResponseBody
	public Result toBuy(@RequestBody CouponUserQuery couponUserQuery) {
		Result result = new Result();
		CouponBaseVo couponBaseVo=couponBaseService.getById(couponUserQuery.getCouponId());
		
		CouponUserVo couponUserVo=couponUserService.getById(couponUserQuery.getId());
		if(CouponUserStatusDictEnum.BE_USED.getCode()==couponUserVo.getStatus()){
			result.addErr("优惠卷已使用");
			return result;
		}
		if(CouponBaseBizzTypeDictEnum.MALL_PRODUCT.getCode()==couponBaseVo.getBizzType()){
			MallProductVo mallProduct = mallProductService.getById(couponBaseVo.getBizzId());
			MallShopVo mallShopVo=mallShopService.getById(mallProduct.getShopId());
			List<MallProductSpecVo> productSpecLst = mallProductSpecService.queryListByProductId(mallProduct.getId());
			mallProduct.setProductSpecLst(productSpecLst);
			mallProduct.setImgString(mallProduct.getImg(),MallConst.IMG_BIG);
			MallSupplier supplier= mallSupplierService.getById(mallProduct.getSupplierId());
			if(supplier != null){
				mallProduct.setSupplierTypeCode(supplier.getType());
				mallProduct.setSupplierTypeStr(MallSupplierTypeDictEnum.getDesc(supplier.getType()));
			}
			result.put("mallShopVo", mallShopVo);
			result.put("mallProduct", mallProduct);
		}else{
			result.addErr("非商城0.01元购买卷");
		}
		result.put("couponUserVo", couponUserVo);
		return result;
	}
	
	/**
	 * 列表
	 * 
	 * @param idleBaseQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/buy")
	@ResponseBody
	public Result buy(@RequestBody Map<String, String> map) {
		Result result = new Result();
		Integer userId = super.getUserId();
		Integer couponId = null;
		String days=couponSysParamService.getValue(CouponConst.PARAM_PEOPLE_BUY_DAYS);
		String days_quantity=couponSysParamService.getValue(CouponConst.PARAM_PEOPLE_BUY_QUANTITY);
		if (StringUtil.isNotBlank(map.get("couponId"))) {
			couponId = Integer.valueOf(map.get("couponId"));
		}
		Integer quantity = 1;
		if (StringUtil.isNotBlank(map.get("quantity"))) {
			quantity = Integer.valueOf(map.get("quantity"));
		}
		if(StringUtil.isNotBlank(days)&&StringUtil.isNotBlank(days_quantity)){//限制用户多少天内兑换同一款优惠卷张数
			Timestamp dayTime=TimeUtil.addDays(TimeUtil.now(), -Integer.valueOf(days));
			CouponUserQuery query=new CouponUserQuery();
			query.setStartAt(dayTime);
			query.setEndAt(TimeUtil.now());
			query.setCouponId(couponId);
			query.setObtainWay(CouponUserObtainWayDictEnum.BUY.getCode());
			query.setUserId(userId);
			int count=couponUserService.queryCount(query);
			if(count+quantity>Integer.valueOf(days_quantity)){
				result.addErr(days+"天内只允许兑换"+days_quantity+"张同一优惠卷。");
				return result;
			}
		}
		UserValue userValue=userValueService.getById(userId);
		CouponBase couponBase=couponBaseService.getById(couponId);
		BigDecimal money=couponBase.getMinusPrice().multiply(new BigDecimal("100"));
		if(userValue.getQuanValue()>money.intValue()*quantity){
			if(couponBase.getQuantity()<quantity){
				result.addErr("优惠卷库存不足");
				return result;
			}
			for(int i=0;i<quantity;i++){
				userMoneyLogService.addMoneyToUser(userId, -money.intValue(), null, UserMoneyLogTypeDictEnum.QUAN);
				couponUserService.addCouponUser(userId, couponId, CouponUserObtainWayDictEnum.BUY, userId);
			}
		}else{
			result.addErr("圈币不足");
		}
		return result;
	}
}
